<script lang="ts" setup name="SystemUser">
import { ElMessage, ElMessageBox } from 'element-plus'
import sysUser from '@/api/modules/system/user'

// 搜索面板
const search = ref({
  name: '',
})

// 分页器
const tableShow = ref({
  // 页数
  page: 1,
  // 调试
  size: 10,
  // 总条数
  total: 0,
  // 加载状态
  loading: true,
})

// 表格
const data = ref([])
const auth = ref([] as any[])
// 获取用户数据
const getList: any = () => {
  // 数据加载时分页器禁用
  tableShow.value.loading = true
  sysUser.index({
    name: search.value.name,
    page: tableShow.value.page,
    size: tableShow.value.size,
  }).then((res) => {
    for (let i = 0; i < res.data.list.length; i++) {
      // 为改变登录状态预留
      res.data.list[i].loading = false
    }
    data.value = res.data.list
    auth.value = res.data.auth
    // 总条数存储
    tableShow.value.total = res.data.total
  }).catch((e) => {
    console.log(e)
  }).finally(() => {
    // 解除分页器禁用
    tableShow.value.loading = false
  })
}

// 切换分页
function pageChange(num: number) {
  tableShow.value.page = num
  getList()
}

// 切换数目
function sizechange(num: number) {
  tableShow.value.size = num
  getList()
}

// 显隐新增用户对话框
const addVisible = ref<boolean>(false)
// 新增按钮加载控制
const addLoading = ref<boolean>(false)
// 新增用户
const addForm = ref({
  username: '',
  password: '',
  is_check: 1,
})
// 打开或关闭新增用户对话框
const add: any = (type: boolean) => {
  addVisible.value = type
  addForm.value = {
    username: '',
    password: '',
    is_check: 1,
  }
}

// 新增用户
const addUser: any = () => {
  // 按钮开启加载禁用
  addLoading.value = true
  sysUser.add(addForm.value).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getList()
      add(false)
    }
    else {
      ElMessage({
        message: res.msg,
        type: 'warning',
      })
    }
  }).catch((e) => {
    console.log(e)
  }).finally(() => {
    // 按钮解除加载禁用
    addLoading.value = false
  })
}

// 改变用户登录权限
const beforeChange: any = (row: any) => {
  // 开关加载动画开启
  row.loading = true
  return new Promise((resolve, reject) => {
    sysUser.changeState({
      id: row.id,
      is_check: row.is_check === 0 ? 1 : 0,
    }).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        return resolve(true)
      }
      else {
        ElMessage({
          message: res.msg,
          type: 'warning',
        })
        return reject(new Error('Error'))
      }
    }).catch((e) => {
      console.log(e)
      return reject(new Error('Error'))
    }).finally(() => {
      // 开关加载动画关闭
      row.loading = false
    })
  })
}

// 删除用户
const deleteUser: any = (id: number) => {
  // 弹窗警告
  ElMessageBox.confirm(
    '您确定删除此用户?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
  ).then(() => {
    // 确认删除
    sysUser.delete({
      id,
    }).then((res: any) => {
      if (res.code === 200) {
        ElMessage({
          message: res.msg,
          type: 'success',
        })
        getList()
      }
      else {
        ElMessage({
          message: res.msg,
          type: 'warning',
        })
      }
    }).catch((e) => {
      console.log(e)
    })
  })
}

// 显隐编辑对话框
const editVisible = ref<boolean>(false)
// 编辑按钮加载控制
const editLoading = ref<boolean>(false)
// 编辑用户
const editForm = ref({
  id: 0,
  is_check: 0,
  gender: undefined,
  username: '',
  password: '',
  nickname: '',
  mobile: '',
  group_id: 0,
})
// 打开或关闭编辑对话框
const edit: any = (type: boolean, row: any = {}) => {
  editVisible.value = type
  if (type) {
    editForm.value = {
      id: row.id,
      is_check: row.is_check,
      gender: row.gender,
      username: row.username,
      password: '',
      nickname: row.nickname,
      mobile: row.mobile,
      group_id: row.group_id,
    }
  }
  else {
    editForm.value = {
      id: 0,
      is_check: 0,
      gender: undefined,
      username: '',
      password: '',
      nickname: '',
      mobile: '',
      group_id: 0,
    }
  }
}

// 新增用户
const editUser: any = () => {
  // 按钮开启加载禁用
  editLoading.value = true
  sysUser.edit(editForm.value).then((res: any) => {
    if (res.code === 200) {
      ElMessage({
        message: res.msg,
        type: 'success',
      })
      getList()
      edit(false)
    }
  }).catch((e) => {
    console.log(e)
  }).finally(() => {
    editLoading.value = false
  })
}

function authName(id: number) {
  for (let i = 0; i < auth.value.length; i++) {
    if (auth.value[i].id === id) {
      return auth.value[i].name
    }
  }
  return ''
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div>
    <page-main>
      <!-- 搜索面板 -->
      <search-bar :show-toggle="false" class="m-b-30">
        <template #default>
          <el-form :model="search" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户名 / 手机号">
                  <el-input v-model="search.name" placeholder="请输入用户名或者手机号，支持模糊查询" clearable />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- <el-row v-show="!fold">
              <el-col :span="24">
                <el-form-item label="角色">
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-form-item>
              <el-button type="primary" @click="getList()">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ep:search" />
                  </el-icon>
                </template>
                搜索
              </el-button>
              <el-button @click="add(true)">
                <template #icon>
                  <el-icon>
                    <svg-icon name="ep:add-location" />
                  </el-icon>
                </template>
                新增
              </el-button>
            </el-form-item>
          </el-form>
        </template>
      </search-bar>
      <!-- 表格 -->
      <el-table
        v-loading="tableShow.loading" :border="true" :data="data" style="width: 100%;"
      >
        <el-table-column prop="id" label="ID" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="gender" label="性别">
          <template #default="scope">
            <el-tag
              v-show="scope.row.gender === 1"
            >
              男
            </el-tag>
            <el-tag
              v-show="scope.row.gender === 0"
              type="danger"
            >
              女
            </el-tag>
            <el-tag
              v-show="scope.row.gender !== 0 && scope.row.gender !== 1"
              type="info"
            >
              保密
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="is_check" label="登录权限">
          <template #default="scope">
            <el-switch
              v-model="scope.row.is_check"
              :active-value="1"
              :inactive-value="0"
              inline-prompt
              active-text="允许"
              inactive-text="拒绝"
              :loading="scope.row.loading"
              :before-change="() => { return beforeChange(scope.row) }"
            />
          </template>
        </el-table-column>
        <el-table-column prop="group_id" label="权限">
          <template #default="scope">
            <span>{{ authName(scope.row.group_id) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="last_login_ip" label="最后登录IP" />
        <el-table-column prop="last_login_time" label="最后登录时间" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button size="small" type="warning" @click="edit(true, scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:currentPage="tableShow.page"
        v-model:page-size="tableShow.size"
        class="m-t-20"
        :disabled="tableShow.loading"
        :page-sizes="[10, 20, 30, 40]"
        :background="true"
        layout="->,otal, sizes, prev, pager, next, jumper"
        :total="tableShow.total"
        @current-change="pageChange"
        @size-change="sizechange"
      />
    </page-main>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="addVisible" title="新增用户" width="25%">
      <el-form
        label-position="right"
        label-width="80px"
        :model="addForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="addForm.username" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="addForm.password" />
        </el-form-item>
        <el-form-item label="允许登录">
          <el-switch
            v-model="addForm.is_check"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="允许"
            inactive-text="拒绝"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="add(false)">取消</el-button>
          <el-button type="primary" :loading="addLoading" @click="addUser()">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editVisible" title="编辑用户" width="25%">
      <el-form
        label-position="right"
        label-width="80px"
        :model="editForm"
      >
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.nickname" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="editForm.password" placeholder="此框输入代表需要修改密码,不想修改密码请勿填写!" />
        </el-form-item>
        <el-form-item label="手机">
          <el-input v-model="editForm.mobile" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="editForm.gender">
            <el-radio :label="1">
              男
            </el-radio>
            <el-radio :label="0">
              女
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="editForm.group_id">
            <el-option
              v-for="(item, index) in auth"
              :key="index"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="允许登录">
          <el-switch
            v-model="editForm.is_check"
            :active-value="1"
            :inactive-value="0"
            inline-prompt
            active-text="允许"
            inactive-text="拒绝"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="edit(false)">取消</el-button>
          <el-button type="primary" :loading="editLoading" @click="editUser()">
            提交
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
